<template>
	<view class="wrap">
		<view class="content">
			<u-form :model="form" ref="uForm">
				<view class="title">用户注册</view>
				<u-form-item prop="username">
					<u-input v-model="form.username" type="text" placeholder="请输入用户名" />
				</u-form-item>
				<u-form-item prop="password">
					<u-input v-model="form.password" type="password" placeholder="请输入密码" />
				</u-form-item>
				<u-form-item prop="pwd2">
					<u-input v-model="form.pwd2" type="password" placeholder="请再次输入密码" />
				</u-form-item>
				<button @tap="register" class="login-btn">立即注册</button>
				<view class="link" @tap="redirectToLogin">已有账号，去登录</view>
			</u-form>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					username: '',
					password: '',
					pwd2: ''
				}
			};
		},
		methods: {
			async register() {
				if (!this.form.username.trim() || !this.form.password.trim() || !this.form.pwd2.trim()) {
					this.$u.toast('请填写完整信息');
					return;
				}
				if (this.form.password !== this.form.pwd2) {
					this.$u.toast('两次输入的密码不一致');
					return;
				}

				try {
					const res = await uniCloud.callFunction({
						name: 'uni-id-cf',
						data: {
							action: 'register',
							params: this.form
						}
					});

					if (res.result.code === 0) {
						this.$u.toast('注册成功');
						this.$u.route('/pages/index/index');
					} else {
						this.$u.toast(res.result.msg);
					}
				} catch (error) {
					console.error('注册失败:', error);
				}
			},
			redirectToLogin() {
				this.$u.route('/pages/login/login');
			}
		}
	};
</script>

<style scoped>
	.wrap {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}

	.content {
		width: 300px;
	}

	.title {
		font-size: 20px;
		font-weight: bold;
		margin-bottom: 20px;
	}

	.login-btn {
		width: 100%;
		margin-top: 20px;
		background-color: #007bff;
		color: #fff;
		border: none;
		padding: 10px;
		border-radius: 5px;
		cursor: pointer;
	}

	.link {
		margin-top: 10px;
		text-align: center;
		color: #007bff;
		cursor: pointer;
	}
</style>